<template>
  <div class="flex_cm container" style="height: 100%">
    <search
      :data="header_list"
      @changeIsShow="
        (e) => {
          header_list[e].isShow = !header_list[e].isShow
          header_list[e].value =
            header_list[e].type == 'input_number' ? ['', ''] : ''
        }
      "
      @search="search_key"
      @reset="
        header_list.forEach((item) => {
          item.value = ''
        }),
          search_key()
      "
    ></search>
    <div class="p_0_10 bg_fff flex1">
      <div class="flex_js p_10_0">
        <div class="c_666 fw">特殊存储空间配置</div>
        <div class="flex">
          <el-button
            type="primary"
            @click="show_box = true"
            v-if="role_list[1].has_role"
            >新增</el-button
          >

          <setTable
            :data="header_list"
            :height_size="height_size"
            @changeShowTable="
              (e) => {
                header_list[e].showTable = !header_list[e].showTable
              }
            "
            @resetTableSet="
              () => {
                header_list.forEach((item) => {
                  item.showTable = true
                })
              }
            "
            @changeHeightSize="
              (e) => {
                height_size = e
              }
            "
          ></setTable>
        </div>
      </div>
      <el-table
        style="text-align: center"
        :data="list"
        :max-height="max_height"
        border
        highlight-current-row
        v-loading="loading"
        :default-sort="{ prop: 'name', order: 'descending' }"
        :row-style="{
          height: height_size == 2 ? '50px' : '',
        }"
        :cell-style="{
          padding: height_size == 3 ? '0' : '',
        }"
      >
        <el-table-column
          type="index"
          label="序号"
          width="80px"
        ></el-table-column>
        <el-table-column
          label="企业名称"
          key="企业名称"
          prop="enterpriseName"
          sortable
          v-if="header_list[0].showTable"
        ></el-table-column>
        <el-table-column
          label="个人名称"
          key="个人名称"
          prop="memberName"
          sortable
          v-if="header_list[1].showTable"
        ></el-table-column>
        <el-table-column
          label="产品类型"
          key="产品类型"
          sortable
          v-if="header_list[2].showTable"
        >
          <template #default="scope">
            <div v-for="i in product_list" :key="i.id">
              <span v-if="i.dictCode == scope.row.productId">{{
                i.dictValue
              }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="存储空间 (单位:G)"
          key="存储空间"
          sortable
          prop="spaceCapacity"
          v-if="header_list[3].showTable"
        ></el-table-column>
        <el-table-column
          label="开始时间"
          key="开始时间"
          sortable
          v-if="header_list[4].showTable"
          ><template #default="scope">
            {{ formatDate(parseInt(scope.row.startTime), 'yyyy-MM-dd') }}
          </template></el-table-column
        >
        <el-table-column
          label="结束时间"
          key="结束时间"
          sortable
          v-if="header_list[5].showTable"
          ><template #default="scope">
            <div v-if="scope.row.endTime === null"></div>
            <div v-else>
              {{ formatDate(parseInt(scope.row.endTime), 'yyyy-MM-dd') }}
            </div>
          </template></el-table-column
        >
        <!-- <el-table-column label="状态" key="状态" v-if="header_list[6].showTable"
          ><template #default="scope">
            <div
              v-if="scope.row.endTime === null || scope.row.endTime > Date.parse(new Date() as any)"
            >
              启用
            </div>
            <div v-else="">已结束</div>
          </template></el-table-column
        > -->
        <el-table-column label="操作" width="120px">
          <template #default="scope: any">
            <el-button
              type="primary"
              @click="update_row(scope.row)"
              v-if="role_list[0].has_role"
              >编辑</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="m_10_0 pagination"
        v-model:currentPage="page_data.current"
        v-model:page-size="page_data.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="list_debounce()"
        @current-change="list_debounce()"
      />
    </div>
    <el-drawer
      v-model="show_box"
      direction="rtl"
      destroy-on-close
      :close-on-click-modal="false"
      @close="resetForm(enterpriseSpaceForm)"
    >
      <template #title>
        <h4 v-if="add_form_data.id == ''">新增</h4>
        <h4 v-else>编辑</h4>
      </template>
      <template #default>
        <el-form
          :model="add_form_data"
          :rules="rules"
          label-width="150px"
          ref="enterpriseSpaceForm"
        >
          <el-form-item label="类型">
            <el-radio-group
              v-model="type"
              class="ml-4"
              :disabled="add_form_data.id != ''"
            >
              <el-radio :label="1">企业</el-radio>
              <el-radio :label="2">个人</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="选择企业" v-if="type == 1" prop="enterpriseId">
            <el-select
              :disabled="add_form_data.id != ''"
              v-model="add_form_data.enterpriseId"
              filterable
              clearable
            >
              <el-option
                v-for="i in enterprise_list"
                :key="i.id"
                :label="i.name"
                :value="i.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="选择个人" v-else prop="memberId">
            <el-select
              :disabled="add_form_data.id != ''"
              clearable
              v-model="add_form_data.memberId"
              filterable
            >
              <el-option
                v-for="i in member_list"
                :key="i.id"
                :value="i.id"
                :label="i.name"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="产品类型" prop="productId">
            <el-select
              v-model="add_form_data.productId"
              :disabled="add_form_data.id != ''"
            >
              <el-option
                v-for="i in product_list"
                :key="i.id"
                :label="i.dictValue"
                :value="i.dictCode"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="存储空间 (单位:G)" prop="spaceCapacity">
            <el-input
              v-model="add_form_data.spaceCapacity"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker
              :disabled-date="startDisabledDate"
              @change="add_form_data.endTime = ''"
              v-model="add_form_data.startTime"
              placeholder="请选择"
              format="YYYY-MM-DD"
              value-format="x"
              type="date"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="结束时间">
            <el-date-picker
              :disabled="add_form_data.startTime == ''"
              :disabled-date="disabledDate"
              v-model="add_form_data.endTime"
              placeholder="请选择"
              format="YYYY-MM-DD"
              value-format="x"
              type="date"
            ></el-date-picker>
          </el-form-item>
          <!-- <el-form-item label="状态">
            <el-radio-group v-model="add_form_data.isEnable" class="ml-4">
              <el-radio :label="true">启用</el-radio>
              <el-radio :label="false">停用</el-radio>
            </el-radio-group>
          </el-form-item> -->
          <div class="m_top10 tr">
            <el-button @click="resetForm(enterpriseSpaceForm)">取消</el-button>
            <el-button type="primary" @click="submit(enterpriseSpaceForm)"
              >确定</el-button
            >
          </div>
        </el-form>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import {
  formatDate,
  debounce,
  handle_search_key,
  check_role,
} from '@/utils/utils' // 权限校验
import search from '@/view/components/search.vue'
import setTable from '@/view/components/setTable.vue'
import { onMounted, ref, onUnmounted, computed } from 'vue'
import axios from '@/service/HttpRequest'
import serviceApi from '@/service/api'
import EventBus from '@/utils/EventBus'
import { FormInstance, ElMessage, ElMessageBox, FormRules } from 'element-plus'
import { useStore } from 'vuex'
const store = useStore()
const enterpriseSpaceForm = ref<FormInstance>()
const attachmentUpload = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入存储空间'))
  }
  if (value < 0) {
    callback(new Error('存储空间不得小于0'))
  } else {
    callback()
  }
}
const rules = ref<FormRules>({
  enterpriseId: [{ required: true, message: '请选择企业', trigger: 'change' }],
  memberId: [{ required: true, message: '请选择个人', trigger: 'change' }],
  productId: [{ required: true, message: '请选择产品', trigger: 'change' }],
  startTime: [
    {
      required: true,
      type: 'date',
      message: '请选择开始时间',
      trigger: 'change',
    },
  ],
  spaceCapacity: [
    { required: true, validator: attachmentUpload, trigger: 'blur' },
  ],
})
const list = ref()
const total = ref()
const type = ref(1)
const max_height = ref()
const loading = ref(false)
const height_size = ref(1)
const header_list = ref([
  {
    label: '企业名称',
    value: '',
    showTable: true,
    type: 'input',
    isShow: true,
    options: [],
  },
  {
    label: '个人名称',
    value: '',
    showTable: true,
    type: 'input',
    isShow: true,
    options: [],
  },
  {
    label: '产品类型',
    value: '',
    showTable: true,
    type: 'select',
    isShow: false,
    options: computed(() => {
      return store.state.product_list
    }),
  },
  {
    label: '存储空间',
    value: '',
    showTable: true,
    type: 'input',
    isShow: false,
    options: [],
  },
  {
    label: '开始时间',
    value: '',
    showTable: true,
    type: 'date',
    isShow: false,
    options: [],
  },
  {
    label: '结束时间',
    value: '',
    showTable: true,
    type: 'date',
    isShow: false,
    options: [],
  },
  //   {
  //     label: '状态',
  //     value: '',
  //     showTable: true,
  //     type: 'select',
  //     isShow: false,
  //     options: [
  //       {
  //         value: true,
  //         label: '启用',
  //       },
  //       {
  //         value: false,
  //         label: '停用',
  //       },
  //     ],
  //   },
])
const startDisabledDate = (time: Date) => {
  return time.getTime() < Date.parse(new Date() as any) - 24 * 60 * 60 * 1000
}
const disabledDate = (time: Date) => {
  // 可选日期
  return (
    time.getTime() <
    parseInt(add_form_data.value.startTime) + 24 * 60 * 60 * 1000
  )
}
const page_data = ref({
  current: 1,
  pageSize: 10,
  enterpriseName: '',
  //   isEnable: '',
  memberName: '',
  endTime: '',
  productId: '',
  spaceCapacity: '',
  startTime: '',
})
const show_box = ref(false)
const add_form_data = ref({
  id: '',
  enterpriseId: '',
  memberId: '',
  memberName: '',
  //   isEnable: true,
  startTime: '',
  endTime: '',
  productId: '',
  spaceCapacity: '',
})
const enterprise_list = computed(() => {
  return store.state.enterprise_list
})
const product_list = computed(() => {
  return store.state.product_list
})
const member_page_data = ref({
  current: 1,
  pageSize: 100000,
})
const member_list = ref()
const role_list = ref([
  { path: 'enterpriseSpace/edit', has_role: false },
  { path: 'enterpriseSpace/post', has_role: false },
])
onMounted(() => {
  role_list.value.forEach((item) => {
    item.has_role = check_role(item.path)
  })
  max_height.value = window.innerHeight - 320 // 不带分页的 table 高度
  EventBus.on('refresh', () => {
    get_list()
    ElMessage.success('操作成功！')
  })
  get_list()
  get_member_list()
})
onUnmounted(() => {
  EventBus.off('refresh')
})
const update_row = (e) => {
  console.log(e)
  type.value = e.enterpriseId == '' || e.enterpriseId == '-1' ? 2 : 1
  add_form_data.value = {
    id: e.id,
    enterpriseId: e.enterpriseId,
    memberId: e.memberId == -1 ? '' : e.memberId,
    memberName: e.memberName,
    // isEnable: e.isEnable,
    startTime: parseInt(e.startTime) as any,
    endTime: e.endTime === null ? '' : (parseInt(e.endTime) as any),
    productId: e.productId,
    spaceCapacity: e.spaceCapacity,
  }
  show_box.value = true
}
const submit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (type.value == 1) {
      add_form_data.value.memberId = ''
    } else {
      add_form_data.value.enterpriseId = ''
    }
    if (valid) {
      axios
        .request({
          url:
            add_form_data.value.id == ''
              ? serviceApi.enterpriseSpace_crud
              : serviceApi.enterpriseSpace_crud + '/' + add_form_data.value.id,
          method: add_form_data.value.id == '' ? 'post' : 'put',
          data: add_form_data.value,
        })
        .then(() => {
          ElMessage.success('操作成功！')
          setTimeout(() => {
            get_list()
            resetForm(formEl)
          }, 1000)
        })
        .catch((err) => {
          ElMessage.error(err)
        })
    }
  })
}
const get_member_list = () => {
  axios
    .request({
      url: serviceApi.platform_member_list,
      method: 'post',
      data: handle_search_key(member_page_data.value),
    })
    .then((res) => {
      console.log(res)
      member_list.value = res.data !== null ? res.data.content : []
    })
    .catch((err) => {
      ElMessage.error(err)
    })
}
const get_list = () => {
  let data = JSON.parse(JSON.stringify(handle_search_key(page_data.value)))
  data.enterpriseName.type = 'INNER_LIKE'
  data.memberName.type = 'INNER_LIKE'
  axios
    .request({
      url: serviceApi.enterpriseSpace_list,
      method: 'post',
      data: data,
    })
    .then((res) => {
      console.log(res)
      list.value = res.data !== null ? res.data.content : []
      total.value =
        res.data !== null ? parseInt(res.data.totalElements) : total.value
    })
}
let list_debounce = debounce(200, get_list)
const search_key = () => {
  page_data.value = {
    current: 1,
    pageSize: 10,
    enterpriseName: header_list.value[0].value,
    memberName: header_list.value[1].value,
    productId: header_list.value[2].value,
    spaceCapacity: header_list.value[3].value,
    startTime: header_list.value[4].value,
    endTime: header_list.value[5].value,
    // isEnable: header_list.value[6].value,
  }
  get_list()
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  add_form_data.value = {
    id: '',
    enterpriseId: '',
    memberId: '',
    memberName: '',
    // isEnable: true,
    startTime: '',
    endTime: '',
    productId: '',
    spaceCapacity: '',
  }
  show_box.value = false
}
</script>

<style lang="scss" scoped></style>
